package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"
	"os"
)

// http server
func sayHello(w http.ResponseWriter, r *http.Request) {
	fmt.Println("有人访问了hello接口")
	http.Redirect(w,r,"https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx48dc5e85be6aad90&redirect_uri=http%3a%2f%2fvocaloid.utools.club%2fWeiXinCode&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect", http.StatusFound) //跳转到百度
}
var appid=`wx48dc5e85be6aad90`
var redirect_uri=`http%3a%2f%2fvocaloid.utools.club%2fWeiXinCode`
var response_type=`code`
var scope=`snsapi_userinfo`
var state=`123`
var Access_token string
var openid string
type weiDenCode struct {
	Access_token string
	Expires_in int
	Refresh_token string
	Openid string
	Scope string
}
type weiUserDemo struct {
	Openid string
	Nickname string
	Sex string
	Province string
	City string
	Country string
	Headimgurl string
	Privilege []string
	Unionid string
}
func WeiXinCode(w http.ResponseWriter, r *http.Request) {
	//第一步：用户同意授权，获取code
	fmt.Println(`第一步：用户同意授权，获取code`)
	fmt.Println("有人来到了这里")
	data := r.URL.Query()
	fmt.Println(data.Get("code"))
	fmt.Println(data.Get("state"))
	code:=data.Get("code")
	//第二步：通过code换取网页授权access_token
	//get方法
	fmt.Println(`第二步：通过code换取网页授权access_token`)
	resp, err := http.Get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=`+appid+`&secret=77e8d4ff99f84430ecb49bf4e4b993f8&code=`+code+`&grant_type=authorization_code`)
	if err != nil {
		fmt.Println("get failed, err:", err)
		return
	}
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("read from resp.Body failed,err:", err)
		return
	}
	fmt.Print(string(body))
	weiDenCodeModel:=&weiDenCode{}
	err = json.Unmarshal(body, weiDenCodeModel)
	if err != nil {
		fmt.Println("json unmarshal failed!")
		return
	}
	fmt.Println("转化完成！")
	fmt.Println("Access_token:",weiDenCodeModel.Access_token)
	//第三步：刷新access_token（如果需要）
	fmt.Println(`第三步：刷新access_token（如果需要）`)
	resp, err = http.Get(`https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=`+appid+`&grant_type=refresh_token&refresh_token=`+weiDenCodeModel.Refresh_token)
	if err != nil {
		fmt.Println("get failed, err:", err)
		return
	}
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("read from resp.Body failed,err:", err)
		return
	}
	fmt.Print(string(body))
	weiDenCodeModel2:=&weiDenCode{}
	err = json.Unmarshal(body, weiDenCodeModel2)
	if err != nil {
		fmt.Println("json unmarshal failed!")
		return
	}
	if weiDenCodeModel.Access_token==weiDenCodeModel2.Access_token {
		fmt.Println("用户两次一样没有超时")
		Access_token=weiDenCodeModel.Access_token
		openid=weiDenCodeModel.Openid
	}else {
		fmt.Println("用户两次超时了，使用最新的！")
		Access_token=weiDenCodeModel2.Access_token
		openid=weiDenCodeModel2.Openid
	}
	fmt.Println("第三步结束end")
	//第四步：拉取用户信息(需scope为 snsapi_userinfo)
	resp, err = http.Get(`https://api.weixin.qq.com/sns/userinfo?access_token=`+Access_token+`&openid=`+openid+`&lang=zh_CN`)
	if err != nil {
		fmt.Println("get failed, err:", err)
		return
	}
	defer resp.Body.Close()
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("read from resp.Body failed,err:", err)
		return
	}
	fmt.Print(string(body))
	weiUsermodel1 := &weiUserDemo{}
	err = json.Unmarshal(body, weiUsermodel1)
	if err != nil {
		fmt.Println("json unmarshal failed!")
		return
	}
	fmt.Println("第四步结束了！")
	fmt.Println(weiUsermodel1.Nickname)
	w.Write([]byte(body))
}
func downloadHandler(w http.ResponseWriter, r *http.Request,fileName string,path string) {
	r.ParseForm() //解析url传递的参数，对于POST则解析响应包的主体（request body）
	//注意:如果没有调用ParseForm方法，下面无法获取表单的数据
	//filename  文件名
	//path 文件存放目录
	file, err := os.Open(path + fileName)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer file.Close()
	content, err := ioutil.ReadAll(file)
	fileNames := url.QueryEscape(fileName) // 防止中文乱码
	fmt.Println("fileNames=",path + fileName)
	w.Header().Add("Content-Type", "application/octet-stream")
	w.Header().Add("Content-Disposition", "attachment; filename=\""+fileNames+"\"")

	if err != nil {
		fmt.Println("Read File Err:", err.Error())
	} else {
		w.Write(content)
	}
}

func test_download(w http.ResponseWriter, r *http.Request)  {
	fmt.Println("有人访问了这个接口！");
	//downloadHandler(w,r,"test.txt","E:\\code\\go\\src\\WeiXinCode\\download\\");
	downloadHandler(w,r,"test.txt","./download/");
}
func main() {
	http.Handle("/", http.FileServer(http.Dir("E:/code/go/src/WeiXinCode/download/")))
	http.HandleFunc("/hello", sayHello)
	http.HandleFunc("/WeiXinCode", WeiXinCode)
	http.HandleFunc("/test_download", test_download)

	//http.HandleFunc("/test", LanJieQi.HTTPInterceptor(LanJieQi.SayHello2()))


	err := http.ListenAndServe(":9090", nil)
	if err != nil {
		fmt.Printf("http server failed, err:%v\n", err)
		return
	}
}
